import re

from users.models import User

from django.contrib.auth.backends import ModelBackend
def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }


def get_user_by_account(account):
    try:
        ret=re.match(r'^1[3-9]\d{9}$',account)
        if ret:
            user=User.objects.get(mobile=account)

            return user
        user=User.objects.get(username=account)
        return user
    except User.DoesNotExist:
        return None

class UsernameMobileAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        # from users.utils import get_user_by_account
        user=get_user_by_account(username)
        if user is not None and user.check_password(password):
            return user